package com.xuyl.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuyl.constant.MessageCode;
import com.xuyl.constant.MessageConstant;
import com.xuyl.domain.Operation;
import com.xuyl.domain.User;
import com.xuyl.entity.QueryBean;
import com.xuyl.entity.Result;
import com.xuyl.service.IOperationService;
import com.xuyl.service.IUserService;
import com.xuyl.utils.LocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 所有异常交给异常处理通知处理，只把异常消息抛出给它就行
 * 所有的数据校验都丢给service去做
 *
 * @author nisemono
 * @date 2023-02-27 19:21
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {


    @Autowired
    private IUserService userService;

    @Autowired
    private IOperationService operationService;

    @PostMapping
    public Result saveUserInfo(@RequestBody User user) {
        boolean flag = userService.save(user);
        // 记录操作
        if (flag) {
            Operation operation = new Operation();
            operation.setOperation("save");
            operation.setAfterData(JSON.toJSONString(user));
            operationService.save(operation);
        }
        return new Result(flag, flag ? MessageConstant.SAVE_USER_SUCCESS : MessageConstant.SAVE_USER_FAILED, user);
    }

    @PutMapping
    public Result updateUserInfo(@RequestBody User user) {
        User beforeData = userService.getUserById(user.getId());
        boolean flag = userService.updateUserInfoById(user);
        // 再查一次，记录乐观锁的值，保证最新的version
        User afterData = userService.getUserById(user.getId());
        if (flag) {
            Operation operation = new Operation();
            operation.setOperation("update");
            operation.setBeforeData(JSON.toJSONString(beforeData));
            operation.setAfterData(JSON.toJSONString(afterData));
            operationService.save(operation);
        }
        return new Result(flag, flag ? MessageConstant.UPDATE_USER_SUCCESS : MessageConstant.UPDATE_USER_FAILED, user);
    }


    @DeleteMapping("/{id}")
    public Result deleteUserById(@PathVariable Integer id) {
        // 需要现将数据查出，因为deleted字段为1不能查询
        User user = userService.getUserById(id);
        boolean flag = userService.deleteById(id);
        // 记录操作
        if (flag) {
            Operation operation = new Operation();
            operation.setOperation("delete");
            operation.setAfterData(JSON.toJSONString(user));
            operationService.save(operation);
        }
        return new Result(flag, flag ? MessageConstant.DELETE_USER_SUCCESS : MessageConstant.DELETE_USER_FAILED);
    }

    /**
     * 批量删除
     *
     * @param selectedIds
     * @return
     */
    @PostMapping("/deleteBatch")
    public Result deleteUserBatch(@RequestBody List<Integer> selectedIds) {
        List<User> deletedUsers = new ArrayList<>();
        for (Integer selectedId : selectedIds) {
            deletedUsers.add(userService.getUserById(selectedId));
        }
        boolean flag = userService.deleteBatch(selectedIds);
        if (flag) {
            for (User user : deletedUsers) {
                Operation operation = new Operation();
                operation.setOperation("delete");
                operation.setAfterData(JSON.toJSONString(user));
                operationService.save(operation);
            }
        }
        return new Result(flag, flag ? MessageConstant.DELETE_USER_SUCCESS : MessageConstant.DELETE_USER_FAILED);
    }

    @GetMapping("/{id}")
    public Result queryUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        if (user == null) {
            return new Result(false, MessageConstant.QUERY_USER_FAILED);
        }
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, user);
    }

    /**
     * 条件查询
     *
     * @param currentPage
     * @param pageSize
     * @param queryString
     * @return
     */
    @GetMapping("/{currentPage}/{pageSize}")
    public Result queryUsersByCondition(@PathVariable Integer currentPage, @PathVariable Integer pageSize, String queryString) {
        QueryBean queryBean = new QueryBean(currentPage, pageSize, queryString);
        IPage<User> userPage = userService.getUserInfoPage(queryBean);
        if (userPage.getCurrent() > userPage.getPages()) {
            queryBean.setCurrentPage((int) userPage.getPages());
            userPage = userService.getUserInfoPage(queryBean);
        }
        for (User user : userPage.getRecords()) {
            String address = "";
            if (user.getProvince() != null) {
                address += user.getProvince();
            }

            if (user.getCity() != null) {
                address += user.getCity();
            }

            if (user.getCounty() != null) {
                address += user.getCounty();
            }
            // 地址数据显示处理
            user.setAddress(address + user.getAddress());

        }
        return new Result(true, MessageCode.GET_OK, MessageConstant.QUERY_USER_SUCCESS, userPage);
    }

}
